<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">
        <el-select v-model="take" @change="getDataPage" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in navlists" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="state" @change="getDataPage" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in navlist" :key="item.id" :label="item.name" :value="item.id" v-if='item.name!="完成1"'>
          </el-option>
        </el-select>
        <el-select v-model="pay_type" @change="getDataPage" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in paylist" :key="item.id" :label="item.name" :value="item.id" v-if="item.id!=1&&item.id!=2">
          </el-option>
        </el-select>
        <el-select v-model="timeType" placeholder="请选择" size="mini" style="width: 100px;" @change="getDataPage">
          <el-option
            label="下单时间"
            :value="0">
          </el-option>
          <el-option
            label="发货时间"
            :value="1">
          </el-option>
        </el-select>
        <el-date-picker class="mr10" style="width: 220px;"
          v-model="value2"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="mini"
          align="right" @change="changeTime">
        </el-date-picker>
        <el-input v-model="keyword" style="width: 220px;" placeholder="订单号/用户电话/收货人/商品名称" class="handle-input mr10" size="mini"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getDataPage"  size="mini">搜索</el-button>
        <el-button type="primary" @click="exportExcel"  size="mini">导出</el-button>
         <!-- <el-button type="primary" class="mr10" size="small">
          导入
          <input type="file" ref="filElem" @change="onChange" id="file">
          </el-button
        > -->
        <el-button type="primary" size="mini" @click.native="$refs.filElem.click()">
          导入
          <input type="file" ref="filElem" @change="onChange" id="file" v-show="false">
        </el-button>
      </div>

      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header" border size="mini" :height="$tableHight"
        @selection-change="handleSelectionChange" v-loading="loading" id="out-table">
        <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>
        <el-table-column prop="order" label="订单号" show-overflow-tooltip width="200"></el-table-column>
        <!-- <el-table-column prop="user.nickname" label="购买用户"></el-table-column> -->
        <!-- <el-table-column label="商品信息" width="300">
          <template slot-scope="scope">
            <div v-for="(lin,index) in scope.row.goods" :key="index" style="display: flex;align-items: center;">
              <el-image class="table-td-thumb" :src="lin.img" :preview-src-list="[lin.img]" ></el-image>
              <div class="namelist">
                <p>{{lin.name}}</p >
                <p>数量：{{lin.number}}</p >
                <p>价格：{{lin.price}}</p >
              </div>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column prop="user.nickname" label="购买用户" width="110"></el-table-column>
        <el-table-column prop="user.mobile" label="用户电话" width="110" show-overflow-tooltip></el-table-column>
        <el-table-column  label="商品名字" show-overflow-tooltip width="250">
          <template slot-scope="scope">
            {{ scope.row.goods[0].name }}
          </template>
        </el-table-column>
        <el-table-column  label="商品数量" >
          <template slot-scope="scope">
            <div>
              {{ scope.row.goods[0].number }}
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="商品价格" >
          <template slot-scope="scope">
            <div>
              {{ scope.row.goods[0].price }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额"></el-table-column>
        <el-table-column label="收货人" width="80" show-overflow-tooltip>
          <template slot-scope="scope">
          {{scope.row.name}}
           </template>
        </el-table-column>
        <el-table-column label="收货人电话" width="110">
          <template slot-scope="scope">
            {{scope.row.mobile}}
          </template>
        </el-table-column>

        <el-table-column label="地址信息" show-overflow-tooltip align="center" width="250">
          <template slot-scope="scope">

          {{scope.row.address}}<i class="el-icon-document-copy" @click="copy(scope.row.name+scope.row.mobile+scope.row.address)"></i>
          </template>
        </el-table-column>

        <el-table-column label="下单时间" align="center" width="160" show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.pay_time">
            {{$clearTimer(scope.row.pay_time)}}
          </template>
        </el-table-column>
        <el-table-column label="发货时间" align="center" width="160" show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.state!= 1 && scope.row.state!= 8">
            {{ $clearTimer(scope.row.deliver_time) }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center">
          <template slot-scope="scope">
            {{['消费券', '补贴券', '资产积分', '绿色积分记录', '权益值', '贡献值'][scope.row.pay_type]}}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template slot-scope="scope">
            {{['待付款','待发货','待收货','待评价','完成','售后'][scope.row.state]}}
          </template>
        </el-table-column>

        <el-table-column label="提货方式" align="center">
          <template slot-scope="scope">
            {{['快递','自提'][scope.row.take]}}
          </template>
        </el-table-column>


        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" v-if="scope.row.state!=1"  @click="handleEdit(scope.row,scope.row.state)">详情</el-button>
            <el-button size="mini" type="text" v-if="scope.row.state==1"  @click="handleEdit(scope.row,scope.row.state)">发货</el-button>
            <el-button size="mini" type="text" v-if="scope.row.state == 1" @click="cancelOrder(scope.row)">取消订单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">

        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="query.pageIndex"
          :page-sizes="[20, 30, 40, 50]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>

import excel from '../../utils/excel.js'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  name: 'basetable',
  data() {
    return {
      query: {
        pageIndex: 1,
         pageSize: 20
      },
      state: -1,
      upload: '',
      editVisible: false,
      pageTotal: 0,
      imageUrl: '',
      videoUrl: '',
      type: 0,
      take:-1,
      navlist: [
      {id:-1, name:'全部'},
      // {id:0, name:'待付款'},
      {id:1, name:'待发货'},
      {id:2, name:'待收货'},
      {id:3, name:'完成'},
      {id:4, name:'完成1'},
      {id:5, name:'售后'},
      {id:8, name:'已取消'}
      ],
      navlists: [
        {id:-1, name:'全部'},
      {id:0, name:'快递'},
      {id:1, name:'自提'},
      ],

      paylist:[
        {id:-1, name:'全部'},
        {id:0, name:'余额'},
        {id:1, name:'积分'},
        {id:2, name:'微信'},
        {id:3, name:'支付宝'},
        {id:4, name:'银行卡'},
      ],
      pay_type:-1,
      keyword: '',
      loading:false,
      tableData: [ ],
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value2: '',
      start_time:'',
      end_time:'',
      timeType:0
    };
  },
  created() {
    this.getData()
  },
  methods: {
    getDataPage() {
      this.query.pageIndex = 1
      this.getData()

    },
    setImg(row){
      return
    },
    copy(row) {
      // 创建一个input框
      const input = document.createElement('input')
      // 将指定的DOM节点添加到body的末尾
      document.body.appendChild(input)
      // 设置input框的value值为复制的值
      const address = row
      input.setAttribute('value', address)
      // 选取文本域中的内容
      input.select()
      // copy的意思是拷贝当前选中内容到剪贴板
      // document.execCommand（）方法操纵可编辑内容区域的元素
      // 返回值为一个Boolean，如果是 false 则表示操作不被支持或未被启用
      if (document.execCommand('copy')) {
        document.execCommand('copy')
      }
      // 删除这个节点
      document.body.removeChild(input)
      // 弹窗：复制成功
      this.$message.success('复制成功');
      //
    },
    exportExcel () {//导出

      var token = localStorage.getItem('admin_shop_token')
      //导出
      this.$http({
        url: this.mainurl + 'business/order/',
        method: 'get',
        responseType: 'blob',
        params: {
          pay_type:this.pay_type,start_time:this.start_time,end_time:this.end_time,
        type: this.start_time ? this.timeType : '',
        take:this.take, page: this.query.pageIndex, size: this.query.pageSize,state:this.state,keyword:this.keyword,
          code: 1,
        },
        headers: {
          'Content-Type': 'application/json',
          Business: token
        }
      }).then(res => {
        try {
          FileSaver.saveAs(
            new Blob([res.data], { type: "application/octet-stream;charset=utf-8" }), "订单.xlsx")
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, res.data);
        }
      })

      // var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
      // var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"), xlsxParam);
      // var wbout = XLSX.write(wb, {
      //     bookType: "xlsx",
      //     bookSST: true,
      //     type: "array"
      // });
      // try {
      //     FileSaver.saveAs(
      //         new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
      //         "订单.xlsx"
      //     );
      // } catch (e) {
      //     if (typeof console !== "undefined") console.log(e, wbout);
      // }
      // return wbout;
    },
    //修改size值
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.query.pageSize = val
      this.getData();
    },

     onChange(event) {

          const inputFile = this.$refs.filElem.files[0];
          var formdata = new FormData()
          if(inputFile){
            formdata.append('file',inputFile)
            this.$http({
                url: this.mainurl + 'business/logistics/',
                method: 'post',
                headers: {
                  'Content-Type': 'multipart/form-data',
                  'business': localStorage.getItem('admin_shop_token')
                },
                data: formdata,
                dataType: "json",
                cache: false, //上传文件无需缓存
                processData: false, //用于对data参数进行序列化处理 这里必须false
                contentType: false, //必须
              }).then(res => {
                if(res.errnp==0){
                  this.$message.success('导入成功，订单已发货')
                  this.getData()
                }else{
                  this.$message.error(res.data.errmsg)
                }
              })

          }
        },

    //获取数据
    getData() {
      this.loading=true
      this.request('business/order/', 'get', {pay_type:this.pay_type,start_time:this.start_time,end_time:this.end_time,
        type: this.start_time ? this.timeType : '',
        take:this.take, page: this.query.pageIndex, size: this.query.pageSize,state:this.state,keyword:this.keyword}).then(res => {
        this.tableData = res.data.data
        this.pageTotal = res.data.total
      })
      	this.loading=false
    },
    // 发货
    handleEdit(e,state) {
      this.$router.push({ path: '/order/orderDetails', query: { id: e.order,state:state } });
    },
    // 订单取消
    cancelOrder(row) {
      this.$prompt('请在下方输入取消理由', '确定要取消吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /\S/,
        inputErrorMessage: '内容不能为空'
      }).then(({ value }) => {
        this.request("business/cancelOrder/", "post", { order: row.order,reason:value }).then(
          (res) => {
            if(res.errno==0) {
              this.$message.success(res.errmsg);
              this.getData()
            }
          }
        );

      }).catch(() => {
        // 用户取消操作
      })
    },
    cancel() {
      this.getData();
    },

    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.request('business/order/', 'delete', { ID: row.ID }).then(res => {
            if (res.errno == 0) {
              this.$message.success(res.errmsg);
              this.tableData.splice(index, 1)
              this.getData()
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 添加
    addregion() {
      this.$router.push({ path: '/commodity/addgoods' })
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageIndex', val);
      this.getData();
    },
    changeTime(e){//时间
      console.log(e)
      try {
        this.start_time=this.formatDate(e[0])
        this.end_time=this.formatDate(e[1])
      } catch (error) {
        this.start_time=''
        this.end_time=''
      }

      this.getData()
    },
    formatTen(num) {
        return num > 9 ? (num + "") : ("0" + num);
    },
    formatDate(date) {
        var date = new Date(date)
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        return year + "-" + this.formatTen(month) + "-" + this.formatTen(day)+ " " +this.formatTen(hour)+ ":" +this.formatTen(minute)+ ":" +this.formatTen(second);
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 60px;
  height: 60px;

  .el-image img {
    object-fit: cover;
  }
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.table-td-thumb{
  margin: 0 !important;
}
.namelist{
  margin-left: 10px;
}
/* 使用 /deep/ 或 >>> 来穿透 scoped 样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  /* 设置表头颜色 */
  color: #333;
  /* 设置表头文字颜色 */
}

</style>
